//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package board_dao

import (
	"context"
	"fmt"

	"gitcode.com/eteam/api-server/dao/common"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type MsgReadStateDbItem struct {
	InfoId          string `bson:"_id"` //自动生成
	DrawId          string `bson:"drawId"`
	MemberUserId    string `bson:"memberUserId"`
	LastMsgSendTime int64  `bson:"lastMsgSendTime"`
}

type _MsgReadStateDao struct {
	mc *mongo.Collection
}

func newMsgReadStateDao(db *mongo.Database) (*_MsgReadStateDao, error) {
	mc := db.Collection(common.DB_NS_BOARD + "msg_read_state")
	return &_MsgReadStateDao{mc: mc}, nil
}

func (db *_MsgReadStateDao) genInfoId(drawId, memberUserId string) string {
	return fmt.Sprintf("%s:%s", drawId, memberUserId)
}

func (db *_MsgReadStateDao) Set(ctx context.Context, dbItem *MsgReadStateDbItem) error {
	dbItem.InfoId = db.genInfoId(dbItem.DrawId, dbItem.MemberUserId)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": dbItem.InfoId}, bson.M{"$set": dbItem},
		options.Update().SetUpsert(true))
	return err
}

func (db *_MsgReadStateDao) Get(ctx context.Context, drawId, memberUserId string) (*MsgReadStateDbItem, error) {
	infoId := db.genInfoId(drawId, memberUserId)
	retItem := &MsgReadStateDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": infoId}).Decode(retItem)
	return retItem, err
}
